/**
 * 消息接收处理类
 * by wyy
 */
class GameMsg {
    private _msgBuffer: egret.ByteArray;

    constructor() {
        this._msgBuffer = new egret.ByteArray();
    }

    //发送消息处理
    send(socket: egret.WebSocket, $msg: any): void {
        var obj: any = this.encode($msg["type"], $msg["body"]);
        if (obj) {
            obj.position = 0;
            socket.writeBytes(obj, 0, obj.bytesAvailable);
        }
        Frame.debugConsole(this, "socket发送消息", $msg);
    };
    //接收到消息的处理
    receive(socket: egret.WebSocket) {
        socket.readBytes(this._msgBuffer);
        socket.writeBytes(this._msgBuffer, 0, this._msgBuffer.bytesAvailable);
        let obj = this.decode(this._msgBuffer);
        if (obj) {
            Frame.Message.dispatch(obj.msgType, obj.decodedMsg);
        }
        //TODO double bytearray clear
        if (this._msgBuffer.bytesAvailable == 0) {
            this._msgBuffer.clear();
        }

        Frame.debugConsole(this, "socket接收消息", obj);
    }
    //消息封装
    encode(type: string, body) {
        let msgId = this.protoTypeToId(type);
        let msgCls = egret.getDefinitionByName(type);

        let obj = msgCls.create(body);
        //加密前protobuf
        let buf = msgCls.encode(obj).finish();
        //加密后protobuf
        //let encryptedByte = Frame.encrypt(config["crypto-type"], buf, config["key"]);

        let byte = new egret.ByteArray();
        // 写入msgId
        byte.writeShort(msgId);
        // 写入data
        byte.writeBytes(new egret.ByteArray(buf), 0);
        return byte;

    }

    //消息解析
    public decode(m: any) {
        var bytes: egret.ByteArray = new egret.ByteArray();
        let id = m.readShort();
        let msgType = this.protoIdToType(id);
        let msgCls = egret.getDefinitionByName(msgType);
        m.readBytes(bytes, 0);
        //let decryptedByte = Frame.decrypt(config["crypto-type"], bytes.bytes, config["key"]);
        let decodedMsg = msgCls.decode(bytes.bytes);
        return { msgType, decodedMsg };
    }

    private protoTypeToId($type: string) {
        /*for (let i in ProtoInfo.MsgInfo) {
            if (ProtoInfo.MsgInfo[i] == $type) {
                return Number(i);
            }
        }*/
        return -1;
    }
    private protoIdToType($id: number) {
        return "-1"//ProtoInfo.MsgInfo[$id];
    }
}